#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
http://stackoverflow.com/questions/4763715/tipfy-how-to-display-blob-in-template?lq=1 :
There isn't a built-in template tag for displaying arbitrary data like that. I can think of two approaches:
Write a request handler for serving avatars as images. Based on your example, request handler would just need 
to look up the greeting to get the image data, send an appropriate Content-Type: image/jpeg (or image/png or 
whatever) header and then write the blob data to the response stream.
Then, in your template, you'd display the image like this:

    <img src="/show-avatar/{{ greeting.key().id() }}">

Write a custom template tag/template filter that takes the blob data and generates an appropiate data URL, 
which would encode the image data directly in the HTML document you're generating.
Then, in your template, you'd display the image something like this:

    <img src="{{ greeting.avatar|dataurl }}">

which would result in output along these lines in the template:

    <img src=".......
""" 

"""Code source: 
http://blog.notdot.net/2010/04/Implementing-a-dropbox-service-with-the-Blobstore-API-part-2, 
nik2.py
""" 

import cgi
import datetime
import urllib
import webapp2

import jinja2
import os

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import users

from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp import util

class FileInfo(db.Model):
  blob = blobstore.BlobReferenceProperty(required=True)
  uploaded_by = db.UserProperty(required=True)
  uploaded_at = db.DateTimeProperty(required=True, auto_now_add=True)

class BaseHandler(webapp2.RequestHandler):
  def render_template(self, file, template_args):
    path = os.path.join(os.path.dirname(__file__), "templates", file)
    self.response.out.write(template.render(path, template_args)) 

class FileUploadFormHandler(BaseHandler):
  @util.login_required
  def get(self):
    template_values = {
            'form_url': blobstore.create_upload_url('/upload'),
            'logout_url': users.create_logout_url('/'),
    }
    template = jinja_environment.get_template('upload2.html')
    self.response.out.write(template.render(template_values))

class FileUploadHandler(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    blob_info = self.get_uploads()[0]
    if not users.get_current_user():
      blob_info.delete()
      self.redirect(users.create_login_url("/"))
      return

    file_info = FileInfo(blob=blob_info.key(),
                         uploaded_by=users.get_current_user())
    db.put(file_info)
    """self.redirect("/file/%d" % (file_info.key().id(),))"""
    self.redirect("/file/%d/success" % (file_info.key().id(),))	

class AjaxSuccessHandler(BaseHandler):
  def get(self, file_id):
    self.response.headers['Content-Type'] = 'text/plain'
    self.response.out.write('%s/file/%s' % (self.request.host_url, file_id))

class FileInfoHandler(BaseHandler):
  def get(self, file_id):
    file_info = FileInfo.get_by_id(long(file_id))
    if not file_info:
      self.error(404)
      return
    template_values = {
            'file_info': file_info,
            'logout_url': users.create_logout_url('/'),
    }
    template = jinja_environment.get_template('info1.html')
    self.response.out.write(template.render(template_values))

class FileDownloadHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, file_id):
    file_info = FileInfo.get_by_id(long(file_id))
    if not file_info or not file_info.blob:
      self.error(404)
      return
    self.send_blob(file_info.blob, save_as=True)

app = webapp2.WSGIApplication([('/', FileUploadFormHandler),
                                      ('/upload', FileUploadHandler),
                                      ('/file/([0-9]+)', FileInfoHandler),
                                      ('/file/([0-9]+)/download', FileDownloadHandler),
                                      ('/file/([0-9]+)/success', AjaxSuccessHandler)],
                                      debug=True) 
